package com.raph.server;

import com.raph.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;

public class ServerUtils {
    private static final Logger logger = LoggerFactory.getLogger(ServerUtils.class);
    private static final ConcurrentHashMap<String, Socket> connections = new ConcurrentHashMap<>();
    public static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    private ServerUtils() {
    }

    public static void sendMessage(Socket socket, Message message) {
        try {

            logger.info("发送消息");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            writer.write(message.toString());
            writer.newLine();
            writer.flush();
        } catch (IOException e) {
            logger.error("消息发送异常！");
        }
    }

    public static void addConnection(String username, Socket socket) {
        connections.put(username, socket);
    }

    public static Socket getConnection(String username) {
        return connections.get(username);
    }

    public static void removeConnection(String username) {
        connections.remove(username);
    }

    public static Path getProjectRoot() {
        String currentDir = System.getProperty("user.dir");
        Path currentPath = Paths.get(currentDir);

        if(currentPath.endsWith("target")) {
            return currentPath.getParent();
        }
        else {
            return currentPath;
        }
    }
}
